package com.zwf;

import com.zwf.service.FileConversionService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 * 切面类
 * 上传过来的文件都会进行处理，只要满足规则就会转换为PDF，并生成对应的索引
 */
@Aspect
@Component
public class FileAspect {

    @Resource
    private FileConversionService conversionService;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void pointcut() {}

    @AfterReturning(pointcut = "pointcut()", returning = "retVal")
    public void convertToPdf(JoinPoint jp, Object retVal) {
        CompletableFuture.runAsync(() -> {
            try {
                handleFile(jp.getArgs(), retVal);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void handleFile(Object[] args, Object retVal) {
        for(Object arg : args) {
            if (arg instanceof MultipartFile) {
                conversionService.processFileAsync((MultipartFile) arg);
            } else if (arg instanceof MultipartFile[]) {
                conversionService.processFileAsyncBatch((MultipartFile[]) arg);
            }
        }
    }
}
